/**
 * 
 */
package br.com.skynix.tcmc.converter;

import java.text.ParseException;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.swing.text.MaskFormatter;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import br.com.skynix.tcmc.util.WebUtil;

/**
 * @author mgrb
 * 
 */
@FacesConverter(value = "cnpj_converter")
public class CNPJConverter implements Converter {

	private static Logger LOGGER = Logger.getLogger(CNPJConverter.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		if (StringUtils.isNotBlank(arg2)) {
			return arg2.replace(".", "").replace("/", "").replace("-", "");
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		if (arg2 != null) {
			try {
				MaskFormatter mf = new MaskFormatter("##.###.###/####-##");
				mf.setValueContainsLiteralCharacters(false);

				return mf.valueToString(arg2);
			}
			catch (ParseException exception) {
				String mensage = WebUtil
						.getMensage("geral.converter.fatalError");
				arg0.addMessage(null,
						new FacesMessage(FacesMessage.SEVERITY_FATAL, mensage,
								exception.getLocalizedMessage()));
				LOGGER.fatal(mensage, exception);
			}
		}
		return null;
	}

}
